﻿# define DEBUG_AGENT
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

using System.Windows.Media.Imaging;
using Microsoft.Phone.Scheduler;
using Common.Library;
using OnlineVideos;

using OnlineVideos.Data;
using System.IO.IsolatedStorage;
using System.IO;
using InsertIntoDataBase;
using System.Collections.ObjectModel;
using OnlineVideos.ViewModels;
using System.Windows.Navigation;
using OnlineVideos.UI;
using OnlineVideos.Entities;
using System.Threading.Tasks;

namespace webslice
{
    public partial class PreviewPage : PhoneApplicationPage
    {
       
        public ObservableCollection<ImageSource> images = new ObservableCollection<ImageSource>();
        public int count = 0;
        public string mode = string.Empty;
        public PreviewPage()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(PreviewPage_Loaded);
            App.webinfo = new ShowList();
            App.webinfotable = new WebInformation();
           
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                ModeList.ItemsSource = new List<string>() { "--SelectType--", "numeric", "string" };
                if (!string.IsNullOrEmpty(Constants.WebSliceImagePath))
                {
                    BitmapImage ProductBitmap = new BitmapImage();
                    ProductBitmap.CreateOptions = BitmapCreateOptions.None;
                    using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (IsolatedStorageFileStream local = myIsolatedStorage.OpenFile(Constants.WebSliceImagePath, FileMode.Open, FileAccess.Read))
                        {
                            ProductBitmap.SetSource(local);
                        }
                    }
                    PreviewCan.Visibility = Visibility.Collapsed;
                    ProductImage.Visibility = Visibility.Visible;
                    ProductImage.Source = ProductBitmap;
                    Constants.WebSliceImagePath = string.Empty;
                }
            }
            catch (Exception)
            {
            }
        }
        void PreviewPage_Loaded(object sender, RoutedEventArgs e)
        {
            UrlText.LengthIndicatorVisible = false;
            if (string.IsNullOrEmpty(App.webinfotable.SelectedText)&&Constants.NavigatedToBrowser==true)
            {
                MessageBoxResult resultLocService = MessageBox.Show("please click go on the url field and select and copy the information on the webpage suppose to be tracked by the webtile.", "mising information for the webtile?"  , MessageBoxButton.OKCancel);
               
                Constants.ImageUrls.Clear();
            }
            if (!string.IsNullOrEmpty(App.webinfotable.SelectedText))
                btndone.IsEnabled = true;
            else
                btndone.IsEnabled = false;
            if (Constants.ImageUrls.Count > 0 && images.Count<1)
            {
                images.Clear();
                Imagelist.Visibility = Visibility.Visible;
                Imagelist.ItemsSource = images;
                
                BitmapImage defaultbi = new BitmapImage();
                defaultbi.UriSource = new Uri("http://www.freetexturesblueprints.com/albums/userpics/10001/thumb_tile-armstrong-free-textures.JPG", UriKind.RelativeOrAbsolute);
                defaultbi.CreateOptions = BitmapCreateOptions.None;
                defaultbi.ImageOpened += defaultbi_ImageOpened;
                defaultbi.ImageFailed += defaultbi_ImageFailed;
                
                Tbsite.Text = Constants.BasicUri;
                PreviewSTB.Text = App.webinfotable.SelectedText;
            }
        }

        void defaultbi_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            foreach (string url in Constants.ImageUrls)
            {
                string UrlText1 = string.Empty;
                if (!url.ToLower().StartsWith("http://") && !url.ToLower().StartsWith("https://"))
                {
                    if (url.ToLower().Contains("www."))
                        UrlText1 = "http://" + url;
                    else
                        UrlText1 = "http://www." + url;
                }
                else
                    UrlText1 = url;
                BitmapImage bi = new BitmapImage();
                bi.UriSource = new Uri(UrlText1, UriKind.RelativeOrAbsolute);
                bi.CreateOptions = BitmapCreateOptions.None;
                bi.ImageOpened += bi_ImageOpened;
                bi.ImageFailed += bi_ImageFailed;
            }
        }

        void defaultbi_ImageOpened(object sender, RoutedEventArgs e)
        {
            images.Add((sender as BitmapImage) as ImageSource);
            foreach (string url in Constants.ImageUrls)
            {
                string UrlText1 = string.Empty;
                if (!url.ToLower().StartsWith("http://") && !url.ToLower().StartsWith("https://"))
                {
                    if (url.ToLower().Contains("www."))
                        UrlText1 = "http://" + url;
                    else
                        UrlText1 = "http://www." + url;
                }
                else
                    UrlText1 = url;
                BitmapImage bi = new BitmapImage();
                bi.UriSource = new Uri(UrlText1, UriKind.RelativeOrAbsolute);
                bi.CreateOptions = BitmapCreateOptions.None;
                bi.ImageOpened += bi_ImageOpened;
                bi.ImageFailed += bi_ImageFailed;
            }
        }

        void bi_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            if(++count==Constants.ImageUrls.Count)
                Imagelist.SelectionChanged += Imagelist_SelectionChanged_1;
        }

        void bi_ImageOpened(object sender, RoutedEventArgs e)
        {
           
            images.Add((sender as BitmapImage) as ImageSource);
            if (++count == Constants.ImageUrls.Count)
                Imagelist.SelectionChanged += Imagelist_SelectionChanged_1;
        }


        


        private void btnDone_Click(object sender, RoutedEventArgs e)
        {
           
            
                if (!Storage.FileExists(ResourceHelper.getShowTileImagePath((Task.Run(async()=>await Constants.connection.Table<ShowList>().FirstOrDefaultAsync()).Result != null ? Task.Run(async()=>await Constants.connection.Table<ShowList>().ToListAsync()).Result.Max(i => i.ShowID) + 1 : 1).ToString() + ".jpg")).Result)
                {
                   
                    if (!Storage.DirectoryExists("/Images"))
                    {
                        Storage.CreateDirectory("/Images");
                    }

                    WriteableBitmap wbmp = new WriteableBitmap(PreviewCan, null);
                    using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (var local = myIsolatedStorage.OpenFile(ResourceHelper.getShowTileImagePath((Task.Run(async()=>await Constants.connection.Table<ShowList>().FirstOrDefaultAsync()).Result != null ? Task.Run(async()=>await Constants.connection.Table<ShowList>().ToListAsync()).Result.Max(i => i.ShowID) + 1 : 1).ToString() + ".jpg"), System.IO.FileMode.OpenOrCreate))
                        {
                            wbmp.SaveJpeg(local, 130, 190, 0, 100);
                            local.Close();
                            local.Dispose();
                            myIsolatedStorage.Dispose();
                        }
                    }
                }
            
            SaveToDatabase();
         
            ShellTileHelper.PinTileToStartScreen(Task.Run(async()=>await Constants.connection.Table<ShowList>().ToListAsync()).Result.Max(i => i.ShowID).ToString());
            Constants.ImageUrls.Clear();
            NavigationService.GoBack();
        }
        public void SaveToDatabase()
        {
           
                InsertData<ShowList> insert = new InsertData<ShowList>();
                insert.ParameterList = new ShowList();
                insert.ParameterList.ShowID = Task.Run(async()=>await Constants.connection.Table<ShowList>().FirstOrDefaultAsync()).Result != null ? Task.Run(async()=>await Constants.connection.Table<ShowList>().ToListAsync()).Result.Max(i => i.ShowID) + 1 : 1;
                insert.ParameterList.TileImage = insert.ParameterList.ShowID.ToString() + ".jpg";
                insert.ParameterList.PivotImage = App.webinfo.PivotImage;
                insert.ParameterList.Title = TbItem.Text;
                insert.ParameterList.Status = "Custom";
                insert.ParameterList.CreatedDate = DateTime.Now;
                insert.ParameterList.ClientPreferenceUpdated = DateTime.Now;
                insert.ParameterList.ClientShowUpdated = DateTime.Now;
                insert.ParameterList.Rating = 3;
                insert.Insert();


                InsertData<WebInformation> web = new InsertData<WebInformation>();
                web.ParameterList = new WebInformation();
                web.ParameterList.NavigationUri = App.webinfotable.NavigationUri;
                web.ParameterList.SelectedText = App.webinfotable.SelectedText;
                web.ParameterList.BeforeText = App.webinfotable.BeforeText;
                web.ParameterList.AfterText = App.webinfotable.AfterText;
                web.ParameterList.ShowID = Task.Run(async()=>await Constants.connection.Table<ShowList>().ToListAsync()).Result.Max(i => i.ShowID);
                web.Insert();
                string catname = Tbsite.Text;
                if (Task.Run(async () => await Constants.connection.Table<ShowCategories>().Where(i => i.CategoryName == catname).ToListAsync()).Result.Count == 0)
                {
                    InsertData<ShowCategories> Showcat = new InsertData<ShowCategories>();
                    Showcat.ParameterList = new ShowCategories();
                    Showcat.ParameterList.Abbreviation = Tbsite.Text.Substring(0, 1);
                    Showcat.ParameterList.CategoryName = Tbsite.Text;
                    Showcat.Insert();
                }

                InsertData<CategoriesByShowID> catshow = new InsertData<CategoriesByShowID>();
                catshow.ParameterList = new CategoriesByShowID();
                catshow.ParameterList.ShowID = Task.Run(async()=>await Constants.connection.Table<ShowList>().ToListAsync()).Result.Max(i => i.ShowID);
                catshow.ParameterList.CatageoryID = Task.Run(async () => await Constants.connection.Table<ShowCategories>().Where(i => i.CategoryName == catname).FirstOrDefaultAsync()).Result.CategoryID;
                catshow.Insert();
            
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if(ModeList.SelectedIndex==0)
            {
                listVal.Visibility = Visibility.Visible;
            }
            else if (TbItem.Text.Length == 0)
            {
                TbVal.Visibility = Visibility.Visible;
                TbItem.Focus();
            }
            else
            {
                if (!string.IsNullOrEmpty(UrlText.Text))
                {
                    urlval.Visibility = Visibility.Collapsed;
                    if (!UrlText.Text.ToLower().StartsWith("http://"))
                    {
                        if (UrlText.Text.ToLower().Contains("www."))

                            UrlText.Text = "http://" + UrlText.Text;
                        else
                            UrlText.Text = "http://www." + UrlText.Text;
                    }
                    SearchManager.SaveSearchHistory(UrlText.Text);
                    if(UrlText.Text.Contains("mode"))
                        NavigationService.Navigate(new Uri("/Views/BrowserPage.xaml?url=" + UrlText.Text, UriKind.Relative));
                        else
                        NavigationService.Navigate(new Uri("/Views/BrowserPage.xaml?url=" + UrlText.Text + "&mode=" + mode, UriKind.Relative));
                }
                else
                {
                    urlval.Visibility = Visibility.Visible;
                    //NavigationService.Navigate(new Uri("/Views/BrowserPage.xaml?url=" + @"http://www.rakuten.com/prod/samsung-series-3-s24c350hl-23-6-widescreen-led-monitor-mega-dcr-5ms/250005748.html&" + "mode=" + mode, UriKind.Relative));
                    //UrlText.Text = "http://www.rakuten.com/prod/samsung-series-3-s24c350hl-23-6-widescreen-led-monitor-mega-dcr-5ms/250005748.html&" + "mode=" + mode;
                }
            }
        }





        private void Imagelist_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
           
                    if (Constants.ImageUrls.Count > 1)
                    {
                        NavigationService.Navigate(new Uri("/Views/PhotoChooser.Xaml?ImageSource=" + ((BitmapImage)(sender as ListPicker).SelectedItem).UriSource.ToString(), UriKind.Relative));
                    }
              
        }

        private void ModeList_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            listVal.Visibility = Visibility.Collapsed;
            mode = (sender as ListPicker).SelectedItem.ToString();
        }

        private void TbItem_TextChanged_1(object sender, TextChangedEventArgs e)
        {
            TbVal.Visibility = Visibility.Collapsed;
            Constants.WebSliceTitle = TbItem.Text;
            previewTb.Text = Constants.WebSliceTitle;
        }

       
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            Constants.ImageUrls.Clear();
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode == NavigationMode.Back)
            {
                Constants.NavigatedToBrowser = false;
                Constants.ImageUrls.Clear();
                Constants.WebSliceImagePath = string.Empty;
                Constants.BasicUri = string.Empty;
            }
        }

        private void productImage_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
           
            //App.webinfo.TileImage = ((BitmapImage)(sender as Image).Tag).UriSource.ToString();
            btndone.IsEnabled = true;

        }



    }
}